package fileIO;

/*
 * 文件拆分
 public static void split(File src, int size) 
 throws IOException{
 }	
 abc.zip
 abc.zip.1
 abc.zip.2
 abc.zip.3
 abc.zip.4	
 文件合并
 public static void concat(File[] files, File target) 
 throws IOException {		
 }
 */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;

import mytool.Time;

public class SplitConcatFile {
	public static void main(String[] args) throws IOException {
		// test();

		Time.start();
		split(new File("/home/tarena/Desktop/1.pdf"), 1024 * 1024);
		Time.end();

		Time.start();
		concatTest();
		Time.end();
	}

	private static void concatTest() throws IOException {
		File dir = new File("/home/tarena/Desktop");
		File[] files = dir.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.matches(".*\\.\\d$");
			}
		});
		Arrays.sort(files);
		File f = new File("/home/tarena/Desktop/2.pdf");
		concat(files, f);
	}

	private static void concat(File[] files, File target) throws IOException {
		for (File f : files) {
			BufferedInputStream in = new BufferedInputStream(
					new FileInputStream(f));
			BufferedOutputStream out = new BufferedOutputStream(
					new FileOutputStream(target, true));
			int i;
			while ((i = in.read()) != -1) {

				out.write(i);

			}
			out.flush();
		}

	}

	private static void test() {
		File f = new File("/home/tarena/Desktop/1.pdf");
		System.out.println(f.getName());
		System.out.println(f.length());
	}

	private static void split(File src, int size) throws IOException {
		BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
				src), 4096);

		long srcsize = src.length();
		for (int i = 0; i < (srcsize % size == 0 ? srcsize / size : srcsize
				/ size + 1); i++) {
			int count = 0;
			File f = new File(src.getParent(), src.getName() + "." + (i + 1));
			BufferedOutputStream bout = new BufferedOutputStream(
					new FileOutputStream(f), 4096);
			while (count < size && bin.available() > 0) {
				int j = bin.read();
				bout.write(j);
				count++;
			}
			bout.flush();
			bout.close();
		}
		bin.close();
	}

}
